//
//  NSString+DHString.m
//  新浪微博OC
//
//  Created by DIANGHONG on 2018/4/4.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "NSString+DHString.h"

@implementation NSString (DHString)
#pragma mark --- 获取当前时间戳---10位
+ (NSString *)getNowTime
{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];
    NSString *timeSp = [NSString stringWithFormat:@"%.0f", time];
    return timeSp;
}


/**
 拼接NSDocumentDirectory路径

 @return NSString（拼接好的路径）
 */
- (NSString *)dh_appendDocumentDir{
    
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0];

    return [docPath stringByAppendingPathComponent:self];
}
#pragma mark - 将某个时间戳转化成 时间
+(NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
    
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    
//    NSLog(@"1296035591  = %@",confromTimesp);
//
//
//
    //NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    
    
    
    //NSLog(@"&&&&&&&confromTimespStr = : %@",confromTimespStr);
    
    
    
    return [NSString dateDecription:confromTimesp];
    
}

// 字符串时间—>时间戳
+ (NSString *)cTimestampFromString:(NSString *)theTime {
    // theTime __@"%04d-%02d-%02d %02d:%02d:00"
    // 转换为时间戳
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    // NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    // [formatter setTimeZone:timeZone];
    NSDate* dateTodo = [formatter dateFromString:theTime];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[dateTodo timeIntervalSince1970]];
    return timeSp;
}

- (BOOL)phoneNumberIsTrue
{
    if (self.length != 11)
        
    {
        
        return NO;
        
    }
    return YES;
    
    

//    /**
//
//     * 手机号码:
//
//     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
//
//     * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
//
//     * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
//
//     * 电信号段: 133,149,153,170,173,177,180,181,189
//
//     */
//
//    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
//
//    /**
//
//     * 中国移动：China Mobile
//
//     * 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
//
//     */
//
//    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
//
//    /**
//
//     * 中国联通：China Unicom
//
//     * 130,131,132,145,155,156,170,171,175,176,185,186
//
//     */
//
//    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\\d{8}$";
//
//    /**
//
//     * 中国电信：China Telecom
//
//     * 133,149,153,170,173,177,180,181,189
//
//     */
//
//    NSString *CT = @"^1(3[3]|4[9]|53|7[037]|8[019])\\d{8}$";
//
//
//
//
//
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//
//    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
//
//    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
//
//    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
//
//
//
//    if (([regextestmobile evaluateWithObject:self] == YES)
//
//        || ([regextestcm evaluateWithObject:self] == YES)
//
//        || ([regextestct evaluateWithObject:self] == YES)
//
//        || ([regextestcu evaluateWithObject:self] == YES))
//
//    {
//
//        return YES;
//
//    }
//
//    else
//
//    {
//
//        return NO;
//
//    }
    
    
    
}


/**
 date转字符串方法
 
 @param date 微博创建时间
 @return NSString
 */
+ (NSString *)dateDecription:(NSDate *)date{
    //当前日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateFormatter *fm = [[NSDateFormatter alloc] init];
    
    //判断是否今天
    if ([calendar isDateInToday:date]) {
        
        NSTimeInterval dalta = -(int)date.timeIntervalSinceNow;
        
        if (dalta < 60) {
            return @"刚刚";
        }
        
        if (dalta < 3600){
            return [NSString stringWithFormat:@"%d 分钟前",(int)dalta / 60];
        }
        
        if (dalta > 3600) {
            
            return [NSString stringWithFormat:@"%d 小时前",(int)dalta / 3600];
        }
    }
    
    //判断是否在昨天
    if ([calendar isDateInYesterday:date]) {
        
        fm.dateFormat = @"昨天 HH:mm";
        
        return [fm stringFromDate:date];
    }
    
    
    //一年内判断
    NSUInteger year = [calendar component:NSCalendarUnitYear fromDate:date];
    NSUInteger currentYear = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
    
    if (year == currentYear) {
        
        fm.dateFormat = @"MM-dd HH:mm";
        
        return [fm stringFromDate:date];
    }
    
    fm.dateFormat = @"yyyy-MM-dd HH:mm";
    
    return [fm stringFromDate:date];
    
}


/**
 正则表达式找"<a href="http://weibo.com" rel="nofollow">新浪微博</a>"
 url和最后的新浪微博字段
 
 @param urlString 指针地址的url字符串
 @return 新浪微博字符串
 */
- (NSString *)dh_hrefUrlWithUrlString:(NSMutableString **)urlString{
    
    //"<a href="http://weibo.com" rel="nofollow">新浪微博</a>",
    
    NSString *pattern = @"<a href=\"(.*?)\" .*?\">(.*?)</a>";
    
    NSRegularExpression *regux = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
    
    NSTextCheckingResult *matchs = [regux firstMatchInString:self options:0 range:NSMakeRange(0, self.length)];
    
    NSString *text = nil;
    
    for (int i = 0; i < matchs.numberOfRanges; i++) {
        
        if (i == 0) {
            continue;
        }
        
        NSRange r = [matchs rangeAtIndex:i];
        
        NSString *subStr = [self substringWithRange:r];
        
        
        if (i != (matchs.numberOfRanges - 1)) {
            
            NSString *urlstr = *urlString;
            
            urlstr = subStr;


        }else{
            
            
            text = [subStr copy];
            
            return subStr;

        }
    }
    return nil;
}

- (NSString *)base64EncodedString
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

- (NSString *)base64DecodedString
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:self options:0];
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}


+ (NSString*)getWeekDay:(NSString*)currentStr

{
    
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc]init];//实例化一个NSDateFormatter对象
    
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设定时间格式,要注意跟下面的dateString匹配，否则日起将无效
    
    NSDate*date =[dateFormat dateFromString:currentStr];
    
    NSArray*weekdays = [NSArray arrayWithObjects: [NSNull null],@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",nil];
    
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone*timeZone = [[NSTimeZone alloc]initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit =NSCalendarUnitWeekday;
    
    NSDateComponents*theComponents = [calendar components:calendarUnit fromDate:date];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}
//返回16位大小写字母和数字
+(NSString *)return16LetterAndNumber{
    //定义一个包含数字，大小写字母的字符串
    NSString * strAll = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //定义一个结果
    NSString * result = [[NSMutableString alloc]initWithCapacity:16];
    for (int i = 0; i < 16; i++)
    {
        //获取随机数
        NSInteger index = arc4random() % (strAll.length-1);
        char tempStr = [strAll characterAtIndex:index];
        result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
    }
    
    return result;
}
- (NSString *)md5
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
// urlString下载image
//- (void)dh_stringTodownloaderImageWithCompletion:(void(^)(UIImage *image))completion{
//
//    NSURL *url = [NSURL URLWithString:self];
//
//    [SDWebImageDownloader.sharedDownloader downloadImageWithURL:url options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
//
//        if (image) {
//            completion(image);
//        }
//        
//    }];
//
//}

@end
